import datetime
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy import desc, or_, and_
from app.core.extensions import db
from app.models import User, AdminLog
from app.models.agents import Order, Plan, PaymentLog
from . import admin_blueprint
from app.services.decorators import admin_required


@admin_blueprint.route('/orders', methods=['GET', 'OPTIONS'])
@jwt_required(optional=True)
def get_orders():
    """获取订单列表

    查询参数:
    - page: 页码，默认1
    - per_page: 每页数量，默认20
    - search: 搜索关键词（订单号、用户ID等）
    - status: 状态筛选（PENDING-待支付, PAID-已支付, CLOSED-已关闭）
    - start_date: 开始日期（格式：YYYY-MM-DD）
    - end_date: 结束日期（格式：YYYY-MM-DD）
    - user_id: 按用户ID筛选
    """
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    search = request.args.get('search', '')
    status = request.args.get('status', '')
    start_date = request.args.get('start_date', '')
    end_date = request.args.get('end_date', '')
    user_id = request.args.get('user_id', '')

    # 构建查询
    query = Order.query

    # 根据状态筛选
    if status:
        query = query.filter(Order.status == status)

    # 根据用户ID筛选
    if user_id:
        try:
            user_id = int(user_id)
            query = query.filter(Order.user_id == user_id)
        except (ValueError, TypeError):
            return jsonify({'code': 1, 'message': '用户ID必须是数字'}), 400

    # 根据日期范围筛选
    if start_date:
        try:
            start_datetime = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            query = query.filter(Order.create_time >= start_datetime)
        except ValueError:
            return jsonify({'code': 1, 'message': '开始日期格式不正确'}), 400

    if end_date:
        try:
            end_datetime = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            # 将结束日期设置为当天的23:59:59
            end_datetime = end_datetime.replace(hour=23, minute=59, second=59)
            query = query.filter(Order.create_time <= end_datetime)
        except ValueError:
            return jsonify({'code': 1, 'message': '结束日期格式不正确'}), 400

    # 关键词搜索
    if search:
        query = query.filter(
            or_(
                Order.id.like(f'%{search}%'),
                Order.transaction_id.like(f'%{search}%')
            )
        )

    # 执行分页查询
    pagination = query.order_by(desc(Order.create_time)).paginate(
        page=page, per_page=per_page, error_out=False
    )

    orders = pagination.items

    # 构建响应数据
    result = {
        'code': 0,
        'message': '获取成功',
        'data': {
            'total': pagination.total,
            'pages': pagination.pages,
            'page': page,
            'per_page': per_page,
            'items': [order_to_dict(order) for order in orders]
        }
    }

    return jsonify(result)


@admin_blueprint.route('/orders/<string:order_id>', methods=['GET', 'OPTIONS'])
@jwt_required(optional=True)
def get_order(order_id):
    """获取订单详情"""
    order = Order.query.get_or_404(order_id)
    order_data = order_to_dict(order)
    return jsonify({
        'code': 0,
        'message': '获取成功',
        'data': order_data
    })


@admin_blueprint.route('/orders/close/<string:order_id>', methods=['POST'])
@jwt_required()
@admin_required
def close_order(order_id):
    """关闭订单"""
    order = Order.query.get_or_404(order_id)

    # 检查订单状态
    if order.status != 'PENDING':
        return jsonify({'code': 1, 'message': '只能关闭待支付的订单'}), 400

    # 更新订单状态
    order.status = 'CLOSED'

    # 添加操作日志
    log = AdminLog(
        admin_id=get_jwt_identity(),
        action='关闭订单',
        ip=request.remote_addr,
        details=f'关闭订单 {order.id}'
    )
    db.session.add(log)

    db.session.commit()

    return jsonify({
        'code': 0,
        'message': '订单已关闭',
        'data': order_to_dict(order)
    })


@admin_blueprint.route('/orders/statistics', methods=['GET', 'OPTIONS'])
@jwt_required(optional=True)
@admin_required
def get_order_statistics():
    """获取订单统计数据"""
    # 获取时间范围参数
    start_date = request.args.get('start_date', '')
    end_date = request.args.get('end_date', '')

    start_datetime = None
    end_datetime = None

    # 如果没有指定时间范围，默认查询最近7天
    if not start_date:
        start_datetime = datetime.datetime.now() - datetime.timedelta(days=7)
    else:
        try:
            start_datetime = datetime.datetime.strptime(start_date, '%Y-%m-%d')
        except ValueError:
            return jsonify({'code': 1, 'message': '开始日期格式不正确'}), 400

    if not end_date:
        end_datetime = datetime.datetime.now()
    else:
        try:
            end_datetime = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            # 将结束日期设置为当天的23:59:59
            end_datetime = end_datetime.replace(hour=23, minute=59, second=59)
        except ValueError:
            return jsonify({'code': 1, 'message': '结束日期格式不正确'}), 400

    # 查询指定时间范围内的订单
    orders_query = Order.query.filter(
        Order.create_time >= start_datetime,
        Order.create_time <= end_datetime
    )

    # 统计总订单数
    total_orders = orders_query.count()

    # 统计已支付订单数
    paid_orders = orders_query.filter(Order.status == 'PAID').count()

    # 统计总收入（已支付订单）
    total_income = Order.query.with_entities(db.func.sum(Order.amount)) \
                       .filter(
        Order.create_time >= start_datetime,
        Order.create_time <= end_datetime,
        Order.status == 'PAID'
    ).scalar() or 0

    # 统计每天的订单数和收入
    daily_stats = []
    current_date = start_datetime.date()
    end_date = end_datetime.date()

    while current_date <= end_date:
        day_start = datetime.datetime.combine(current_date, datetime.time.min)
        day_end = datetime.datetime.combine(current_date, datetime.time.max)

        # 统计当天订单数
        day_orders = Order.query.filter(
            Order.create_time >= day_start,
            Order.create_time <= day_end
        ).count()

        # 统计当天已支付订单数
        day_paid_orders = Order.query.filter(
            Order.create_time >= day_start,
            Order.create_time <= day_end,
            Order.status == 'PAID'
        ).count()

        # 统计当天收入
        day_income = db.session.query(db.func.sum(Order.amount)) \
                         .filter(
            Order.create_time >= day_start,
            Order.create_time <= day_end,
            Order.status == 'PAID'
        ).scalar() or 0

        daily_stats.append({
            'date': current_date.strftime('%Y-%m-%d'),
            'total_orders': day_orders,
            'paid_orders': day_paid_orders,
            'income': float(day_income)
        })

        current_date += datetime.timedelta(days=1)

    return jsonify({
        'code': 0,
        'message': '获取成功',
        'data': {
            'total_orders': total_orders,
            'paid_orders': paid_orders,
            'total_income': float(total_income),
            'payment_rate': round(paid_orders / total_orders * 100, 2) if total_orders > 0 else 0,
            'daily_stats': daily_stats
        }
    })


@admin_blueprint.route('/orders/export', methods=['GET', 'OPTIONS'])
@jwt_required(optional=True)
@admin_required
def export_orders():
    """导出订单数据"""
    # 获取筛选参数
    status = request.args.get('status', '')
    start_date = request.args.get('start_date', '')
    end_date = request.args.get('end_date', '')

    # 构建查询
    query = Order.query

    # 根据状态筛选
    if status:
        query = query.filter(Order.status == status)

    # 根据日期范围筛选
    if start_date:
        try:
            start_datetime = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            query = query.filter(Order.create_time >= start_datetime)
        except ValueError:
            return jsonify({'code': 1, 'message': '开始日期格式不正确'}), 400

    if end_date:
        try:
            end_datetime = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            # 将结束日期设置为当天的23:59:59
            end_datetime = end_datetime.replace(hour=23, minute=59, second=59)
            query = query.filter(Order.create_time <= end_datetime)
        except ValueError:
            return jsonify({'code': 1, 'message': '结束日期格式不正确'}), 400

    # 执行查询，限制最多导出1000条数据
    orders = query.order_by(desc(Order.create_time)).limit(1000).all()

    # 构建导出数据
    export_data = [
        {
            'id': order.id,
            'user_id': order.user_id,
            'user_name': order.user.nick_name if order.user else '',
            'amount': str(order.amount),
            'title': order.title,
            'status': order.status,
            'transaction_id': order.transaction_id or '',
            'create_time': order.create_time.strftime('%Y-%m-%d %H:%M:%S') if order.create_time else '',
            'paid_time': order.paid_time.strftime('%Y-%m-%d %H:%M:%S') if order.paid_time else '',
            'times': order.times,
            'plan_name': order.plan.name if order.plan else ''
        }
        for order in orders
    ]

    # 记录操作日志
    log = AdminLog(
        admin_id=get_jwt_identity(),
        action='导出订单',
        ip=request.remote_addr,
        details=f'导出订单数据，共{len(export_data)}条'
    )
    db.session.add(log)
    db.session.commit()

    return jsonify({
        'code': 0,
        'message': '导出成功',
        'data': export_data
    })


def order_to_dict(order, NOLOG=True):
    """将订单对象转换为字典"""
    # 获取关联的用户和套餐信息
    user = User.query.get(order.user_id) if order.user_id else None
    plan = Plan.query.get(order.plan_id) if order.plan_id else None

    result = {
        'id': order.id,
        'user_id': order.user_id,
        'amount': str(order.amount),
        'total_fee': order.total_fee,
        'plan_id': order.plan_id,
        'times': order.times,
        'platform_type': order.platform_type,
        'title': order.title,
        'status': order.status,
        'transaction_id': order.transaction_id,
        'prepay_id': order.prepay_id,
        'create_time': order.create_time.strftime('%Y-%m-%d %H:%M:%S') if order.create_time else None,
        'paid_time': order.paid_time.strftime('%Y-%m-%d %H:%M:%S') if order.paid_time else None,
        'notify_time': order.notify_time.strftime('%Y-%m-%d %H:%M:%S') if order.notify_time else None,
        'ip': order.ip,
        'openid': order.openid,
        'remark': order.remark,
        'user': {
            'nick_name': user.nick_name,
            'mobile': user.mobile
        } if user else None,
        'plan': {
            'name': plan.name,
            'amount': str(plan.amount) if plan else None
        } if plan else None
    }

    if NOLOG:
        # 获取最近一条支付成功记录
        payment = PaymentLog.query.filter(
            and_(
                PaymentLog.order_id == order.id,
                PaymentLog.status == "SUCCESS"
            )
        ).order_by(desc(PaymentLog.create_time)).first()

        result['payment'] = {
            'payment_type': payment.payment_type,
            'transaction_id': payment.transaction_id,
            'amount': str(payment.amount),
        } if payment else None

    return result
